﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.InteropServices;
using System.Web.Security;
using System.Security;
using System.Security.Cryptography;
using LiveWebServiceBase;

namespace LiveWebServiceAdmin
{
    public partial class Login : System.Web.UI.Page
    {
        protected override void OnInit(EventArgs e)
        {
            lbMainError.Visible = false;
            lbMainError.ApplyStyle(rfvLogin.ControlStyle);

            if (Session["JSChecked"] == null)
            {
                Session["JSChecked"] = "Checked";
                string path = string.Empty;

                if (Request.QueryString.Count > 0)
                    path = Request.Url + "&JScript=1";
                else
                    path = Request.Url + "?JScript=1";

                Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect",
                  "window.location.href='" + path + "';", true);
            }


            if (Request.QueryString["JScript"] == null && Session["JSEnabled"] == null)
            {
                lbMainError.Visible = true;
                lbMainError.Text = "JavaScript is not enabled. Enable JavaScript and reload page.";
                btnLogin.Enabled = false;
            }
            else
            {
                Session["JSEnabled"] = true;
                string userdata = GetCookie("LAemWS");

                if (!string.IsNullOrEmpty(userdata))
                {
                    string username = LiveWebServiceBase.Security.Authorization.DecryptString(userdata).Split(' ')[0];
                    string password = LiveWebServiceBase.Security.Authorization.DecryptString(userdata).Split(' ')[1];

                    ProceedUser(username, password);
                }
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            ProceedUser(tbLogin.Text, tbPassword.Text);
        }

        protected void ProceedUser(string UserLogin, string Password)
        {
            try
            {
                string domainName = LiveWebServiceBase.Security.Authorization.GetDomainName(UserLogin);
                string userName = LiveWebServiceBase.Security.Authorization.GetUsername(UserLogin);
                IntPtr token = IntPtr.Zero;

                bool IsAdmin = Settings.UserInfo.IsAdminUser(userName);
                bool IsUser = Settings.UserInfo.IsServiceUser(userName);
                bool result = false;

                result = LiveWebServiceBase.Security.Authorization.LogonUser(userName, domainName, Password, 2, 0, ref token);


                if (result && (IsAdmin || IsUser))
                {
                    if (cbIsRemeber.Checked)
                    {
                        string userinfo = UserLogin + " " + Password;

                        SetCookie("LAemWS", LiveWebServiceBase.Security.Authorization.EncryptString(userinfo), 1);

                        //Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(14);
                        //Response.Cookies["UserName"].Value = userName;
                    }

                    //if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
                    //{
                    //    FormsAuthentication.RedirectFromLoginPage(UserLogin, false);
                    //}
                    //else
                    {
                        FormsAuthentication.SetAuthCookie(UserLogin, false);
                        Session["userData"] = LiveWebServiceBase.Security.Authorization.EncryptString(userName + ";" + domainName + ";" + Password);

                        if (IsAdmin)
                            Response.Redirect("/Users.aspx", false);
                        else if (IsUser)
                            Response.Redirect("/Organizations.aspx?manageuser=" + userName, false);
                    }
                }
                else
                {
                    lbMainError.Visible = true;
                    lbMainError.Text = "Invalid username or password.";
                }
            }
            catch (Exception ex)
            {
                lbMainError.Visible = true;
                lbMainError.Text = ex.Message;
            }
        }

        protected bool SetCookie(string cookiename, string cookievalue, int iDaysToExpire)
        {
            try
            {
                HttpCookie objCookie = new HttpCookie(cookiename);
                Response.Cookies.Clear();
                Response.Cookies.Add(objCookie);
                objCookie.Values.Add(cookiename, cookievalue);
                DateTime dtExpiry = DateTime.Now.AddDays(iDaysToExpire);
                Response.Cookies[cookiename].Expires = dtExpiry;
            }
            catch
            {
                return false;
            }
            return true;
        }

        protected string GetCookie(string cookiename)
        {
            string cookyval = "";
            try
            {
                cookyval = Request.Cookies[cookiename].Values[0];
            }
            catch
            {
                cookyval = "";
            }
            return cookyval;
        }
    }
}
